package com.hnyyjsxy.web.servlet;

import com.fasterxml.jackson.databind.ObjectMapper;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * BeanServlet类继承HttpServlet,重写父类中的service（）方法
 * 获取请求路径，利用字符串截取函数获取最后的路径，这个就是servlet对应的方法名
 * 使用反射获取方法对象
 * 执行方法
 * @date 2021/01/30
 */

public class BeanServlet extends HttpServlet {

    /*
    进行子类方法的分发
     */
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1. 获取请求路径
        String requestURI = req.getRequestURI();
        //2. 字符串截取获取最后的请求路径
        String methodName = requestURI.substring(requestURI.lastIndexOf('/') + 1);

        //3. 获取方法对象
        try {
            Method method = this.getClass().getMethod(methodName, HttpServletRequest.class, HttpServletResponse.class);
            //4. 执行方法
            method.invoke(this,req,resp);
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
    }

    /**
     * 将参数转为json对象，并响应的前端
     * @param object
     * @param resp
     */
    public void respondOnly(Object object,HttpServletResponse resp){
        resp.setContentType("application/json;charset=utf-8");
        try {
            new ObjectMapper().writeValue(resp.getOutputStream(),object);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
